package com.schedule.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${schedule.path}")
    private String imagePath;

    @PostMapping("/upload")
    public void upload(MultipartFile file) throws IOException {
        //原文件名
        String originalFilename = file.getOriginalFilename();

        //获得文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //新文件名
        String fileName=UUID.randomUUID().toString()+suffix;

        //新建目录
        File dir=new File(imagePath);

        //判断目录是否存在,若目录不存在则创建目录
        if (!dir.exists())
            dir.mkdirs();

        //file为临时文件，需要转存到指定位置，否则本次请求后图片会被删除
        file.transferTo(new File(imagePath+fileName));


    }


    @GetMapping("/download")
    public void download(String name,HttpServletResponse response) throws IOException {


        //输入流，通过输入流读取文件内容
        FileInputStream inputStream = new FileInputStream(imagePath+name);

        //输出流，通过输出流将文件写回浏览器，使浏览器得以展示图片
        ServletOutputStream servletOutputStream = response.getOutputStream();

        //设置发送到客户端的响应的内容类型为图片
        response.setContentType("image/jpeg");

        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1) {//read()返回-1时表示已经读取完毕
            //写回浏览器
            servletOutputStream.write(bytes, 0, len);
            //刷新
            servletOutputStream.flush();
        }

        //关闭流
        servletOutputStream.close();
        inputStream.close();
    }
}
